package com.lyandwc.lw_bbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyandwc.lw_bbs.entity.Category;
import com.lyandwc.lw_bbs.service.CategoryService;
import com.lyandwc.lw_bbs.utils.ResponseUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/categories")
public class CategoryController {
    private CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject listCategories() {
        return ResponseUtils.success(categoryService.listCategories());
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @RequestMapping(method = RequestMethod.POST)
    public JSONObject addCategory(
            @RequestBody Map<String, String> map
    ) {
        Category category = new Category();

        String name = map.get("name");
        String description = map.get("description");
        String avatar = map.get("avatar");
        int fatherCategoryId = Integer.parseInt(map.getOrDefault("fatherCategoryId", "-1"));

        category.setName(name);
        category.setDescription(description);
        category.setAvatar(avatar);

        categoryService.insertCategory(category, fatherCategoryId);

        return ResponseUtils.success(category);
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public JSONObject delCategory(
            @PathVariable int id
    ) {
        categoryService.removeById(id);
        return ResponseUtils.success(null);
    }
}
